import logging
import colorlog
import re
import os
from logging.handlers import TimedRotatingFileHandler

LogName = "ssjhs"


def setupLog(log2file=True):
    log_colors_config = {
        "DEBUG": "white",  # cyan white
        "INFO": "green",
        "WARNING": "yellow",
        "ERROR": "red",
        "CRITICAL": "bold_red",
    }

    logger = logging.getLogger(LogName)
    log_path = os.path.join(os.getcwd() + "/logFiles", LogName)

    if not os.path.isdir(os.getcwd() + "/logFiles"):
        os.makedirs(os.getcwd() + "/logFiles")

    # 输出到控制台
    console_handler = logging.StreamHandler()
    
    if log2file:
        # 输出到文件
        # file_handler = logging.FileHandler(filename='system.log', mode='a', encoding='utf8')
        file_handler = TimedRotatingFileHandler(
            filename=log_path, when="MIDNIGHT", interval=1, backupCount=0)
        # file_handler = TimedRotatingFileHandler(log_path, when="S", interval=1, backupCount=0)

        # # 定义日志输出格式
        file_handler.setFormatter(logging.Formatter(
            "[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s"))

    # 日志输出格式
    # file_formatter = logging.Formatter(fmt="[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
    console_formatter = colorlog.ColoredFormatter(
        fmt="%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s", datefmt="%Y-%m-%d %H:%M:%S", log_colors=log_colors_config)
    console_handler.setFormatter(console_formatter)
    # file_handler.setFormatter(file_formatter)

    # 重复日志问题：
    # 1、防止多次addHandler；
    # 2、loggername 保证每次添加的时候不一样；
    # 3、显示完log之后调用removeHandler
    if not logger.handlers:
        logger.addHandler(console_handler)
        if log2file:
            logger.addHandler(file_handler)

    console_handler.close()
    if log2file:
        file_handler.close()

    # 日志级别，logger 和 handler以最高级别为准，不同handler之间可以不一样，不相互影响
    logger.setLevel(logging.DEBUG)
    console_handler.setLevel(logging.DEBUG)
    
    if log2file:
        file_handler.setLevel(logging.DEBUG)


if __name__ == "__main__":
    setupLog()
    logger = logging.getLogger("ssjhs")
    logger.debug("debug")
    logger.info("info")
    logger.warning("warning")
    logger.error("error")
    logger.critical("critical")
